// 时间戳转时分秒(如充电时长)，d为补足时间戳，比如两个时间戳差值209200，需要1000的补足
function formatTime(time, d = 1) {
  if (typeof time !== 'number' || time < 0) {
    return time;
  }

  const hour = Math.floor(time / (3600 * d));
  time = time % (3600 * d);
  const minute = Math.floor(time / (60 * d));
  time = time % (60 * d);
  const second = Math.floor(time / d);

  return [hour, minute, second]
    .map(function (n) {
      return n.toString().padStart(2, '0');
    })
    .join(':');
}

// 时间戳转YYYY-MM-DD HH:mm:ss
function timestampToTime(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
  const date = new Date(timestamp);

  const formatParts = {
    YYYY: date.getFullYear(),
    MM: String(date.getMonth() + 1).padStart(2, '0'),
    DD: String(date.getDate()).padStart(2, '0'),
    HH: String(date.getHours()).padStart(2, '0'),
    mm: String(date.getMinutes()).padStart(2, '0'),
    ss: String(date.getSeconds()).padStart(2, '0'),
  };

  // 使用一个替换函数来根据格式字符串生成结果
  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, (match) => formatParts[match]);
}

// 主要用于聊天显示的时间
const dateUtils = {
  UNITS: {
    年: 31557600000,
    月: 2629800000,
    天: 86400000,
    小时: 3600000,
    分钟: 60000,
    秒: 1000,
  },
  humanize: function (milliseconds) {
    let humanize = '';
    for (let key in this.UNITS) {
      if (milliseconds >= this.UNITS[key]) {
        humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
        break;
      }
    }
    return humanize || '刚刚';
  },
  format: function (dateStr) {
    let date = this.parse(dateStr);
    let diff = Date.now() - date.getTime();
    if (diff < this.UNITS['天']) {
      return this.humanize(diff);
    }
    let _format = function (number) {
      return number < 10 ? '0' + number : number;
    };
    return (
      date.getFullYear() +
      '/' +
      _format(date.getMonth() + 1) +
      '/' +
      _format(date.getDate()) +
      '-' +
      _format(date.getHours()) +
      ':' +
      _format(date.getMinutes())
    );
  },
  parse: function (str) {
    //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
    let a = str.split(/[^0-9]/);
    return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
  },
};

// 防止多次点击，需要在使用页面设置noClick: true
function noMultipleClicks(methods, params, isAuto = true) {
  // methods是需要点击后需要执行的函数， params是点击需要传的参数
  let that = this;
  if (that.noClick) {
    // 第一次点击
    that.noClick = false;
    if (params && params !== '') {
      // params是执行函数需要传的参数
      methods(params);
    } else {
      methods();
    }
    if (isAuto) {
      setTimeout(() => {
        that.noClick = true;
      }, 2000);
    }
  } else {
    // 这里是重复点击的判断
    uni.showToast({
      title: '请勿重复操作',
      icon: 'none',
      mask: true,
      duration: 2000,
    });
  }
}

// 时间戳差值
function getTimeDiff(res, callback) {
  if (!res) return;
  // 定义两个日期时间
  const eTime = res.orderStatus == 1 ? res.nowTime : res.endTime;
  const datetime1 = new Date(res.startTime.replace(/-/g, '/'));
  const datetime2 = eTime ? new Date(eTime.replace(/-/g, '/')) : new Date();
  // 将日期时间转换为时间戳（单位：毫秒）
  const timestamp1 = datetime1.getTime();
  const timestamp2 = datetime2.getTime();
  // 计算时间差（单位：毫秒）
  const timeDiff = Math.abs(timestamp2 - timestamp1);
  // 回调函数
  callback && callback(timeDiff);
}

// 对象转url参数
function jsonToUrlParam(json) {
  return Object.keys(json)
    .map((key) => key + '=' + json[key])
    .join('&');
}

// 数据字典回显
function selectDictLabel(datas, value) {
  if (value === undefined || !datas) {
    return '';
  }
  const actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value == '' + value) {
      actions.push(datas[key].label);
      return true;
    }
  });
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join('');
}

// tree数据处理
function processingTree(
  data,
  id = 'id',
  parentId = 'parentId',
  children = 'children'
) {
  const config = {
    id,
    parentId,
    childrenList: children,
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  for (let d of data) {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }
  const adaptToChildrenList = (o) => {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  };

  for (const t of tree) {
    adaptToChildrenList(t);
  }

  return tree;
}

// 获取菜单数据
function getMenuItem(code) {
  let r = (uni.getStorageSync('menu') || []).filter(
    (item) => item.menuXcxNo === code
  );
  return r.length === 0 ? null : r[0];
}

export default {
  dateUtils,
  formatTime,
  getTimeDiff,
  processingTree,
  jsonToUrlParam,
  selectDictLabel,
  timestampToTime,
  noMultipleClicks,
  getMenuItem,
};
